package com.zero.demo.jms.util;


import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zengzr
 * @desc
 * @Date 2019/5/6 10:44
 */
public class LockUtils {

    private static int lruCacheLength=2000;
    private static Map<Class<?>, Map<Object, Lock>> classMap=new ConcurrentHashMap<Class<?>, Map<Object, Lock>>();


    /**
     * 获取Class中key的锁
     * @param type	Class类
     * @param key	key值
     * @return
     * zengzr	 2015年7月11日
     */
    public static Lock getLock(Class<?> type,Object key){
        Lock lock=null;
        if(key==null){
            throw new RuntimeException("获取锁对象异常：传入key不能为空");
        }
        Map<Object, Lock> lockMap=null;
        if (!classMap.containsKey(type)) {
            //如果未包含，则给其创建Map对象
            synchronized (LockUtils.class) {
                if (!classMap.containsKey(type)) {
                    lockMap=new LRUCache<Object, Lock>(lruCacheLength);
                    classMap.put(type, lockMap);
                }
            }
        }
        lockMap=classMap.get(type);

        if (!lockMap.containsKey(key)) {
            //如果未包含，则给其创建锁对象
            synchronized (LockUtils.class) {
                if (!lockMap.containsKey(key)) {
                    lock=new ReentrantLock();
                    lockMap.put(key, lock);
                }
            }
        }
        lock=lockMap.get(key);
        return lock;
    }
    /**
     * 尝试释放锁
     * @param lock  所对象
     * @return
     * @author  zengzr  on 2017年1月16日 下午4:32:19
     * @version 1.0.0
     */
    public static boolean  unlock(Lock lock){
        boolean ret=false;
        if (lock!=null) {
            lock.unlock();
            ret=true;
        }

        return ret;
    }
}
